<template>
    <div>
    <basic-container>
      <avue-crud
        :option="tableOption"
        :data="tableData"
        :table-loading="tableLoading"
        :page="page"
        ref="crud"        
        v-model="formData"
        @row-save="handleSave"
        @row-del="handleDel"
        @refresh-change="handleRefreshChange"
        
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        @selection-change="handleSelectionChange"
        @row-update="handleUpdate"
        @search-change="handleSearchChange"
      >
      <template slot="goodsIdForm">
        <div>
          <div>
              {{formData.title}}
          </div>
          <el-button @click="handleSelectGoods" size="mini" type="primary">选择商品</el-button>
        </div>
      </template>
      <template slot="menu" scope="scope">
        <div>
           <el-button
                  type="text"
                  @click.stop="handleResolve(scope.row)"
                  icon="el-icon-edit"
                  size="mini"
                  v-if="scope.row.status != 10"
                  v-perm="'/admin/goods_selected/check'"
                >审核通过</el-button>
                <el-button
                  type="text"
                  @click.stop="handleReject(scope.row)"
                  icon="el-icon-edit"
                  size="mini"
                  v-if="scope.row.status != 5"
                  v-perm="'/admin/goods_selected/check'"
                >审核拒绝</el-button>
        </div>
      </template>
      <template slot="menuLeft">
        
        <!-- <el-button
          type="danger"
          @click="handleBathDelRows"
          :loading="bachDeleting"
          v-perm="'/admin/goods_selected/batch-remove'"
          icon="el-icon-remove"
          size="small"
        >批量删除</el-button> -->
        <el-button
              v-waves
              size="small"
              class="filter-item"
              type="primary"
              icon="el-icon-edit"
              v-perm="'/admin/goods_selected/check'"
              @click="handleBatchResolve"
            >批量审核通过</el-button>
            <el-button
              v-waves
              size="small"
              class="filter-item"
              v-perm="'/admin/goods_selected/check'"
              type="danger"
              icon="el-icon-edit"
              @click="handleBatchReject"
            >批量审核拒绝</el-button>
        <el-button
        type="primary"
        @click="handleExport"
        :loading="downloadLoading"
        icon="el-icon-download"
        v-perm="'/admin/goods_selected/export'"
        size="small"
      >导出</el-button>
      </template>
      </avue-crud>
      </basic-container>
      <el-dialog :visible.sync="goodsSelectedDialogShowed" title="优选商品选择" width="1000px">
        <goodsIndex @onSelectGoods="handleOnSelectGoods" :goodsType="-1" :selectable="true"></goodsIndex>
      </el-dialog>
    </div>
  </template>
  <script>
  import { validatenull } from "@/util/validate";
  import { filterForm } from "@/util/util";
  // import { DIC } from "@/const/dic";
  import {  getLabelFromDicV2 } from "@/const/dic";
  import { nowDate } from "../../util/date";
  import * as apiObj from "../../api/goodsSelected";
  import { goodsSelectedTableOption} from "@/const/goodsSelected/goodsSelectedTableOption.js";
  import goodsIndex from '../goods/index';
  export default {
    components:{
      goodsIndex
    },
    data() {
      return {
        formData:{},
        bachDeleting: false,
        tableOption: {}, //表格设置属性
        tableData: [], //表格的数据
        downloadLoading:false,
        goodsSelectedDialogShowed:false,
        tableLoading: false,
        tableQueryParam: {},
        page: {
          total: 0, //总页数
          currentPage: 1, //当前页数
          pageSize: 10 //每页显示多少条
        }
      };
    },
    created() {
      //初始化数据格式
      this.tableOption = goodsSelectedTableOption;
      this.handleList();
    },
    methods: {
      handleSelectGoods(){
        this.goodsSelectedDialogShowed = true;
      },
        handleSelectionChange(val) {
      this.multipleSelection = val;
    },
      handleOnSelectGoods(row){
        this.formData.title = row.title;
        this.formData.goodsId = row.id;
        this.goodsSelectedDialogShowed = false;
      },
      handleCurrentChange(page) {
        this.page.currentPage = page;
        this.handleList();
      },
      handleSizeChange(size) {
        this.page.pageSize = size;
        this.handleList();
      },
      handleBatchResolve(){
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.$prompt('确认审核通过所选商品吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.check({
              id:this.multipleSelection.map(el=>el.id).join(','),
              status:10,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBatchReject(){
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.showError("请选择至少一条记录");
        return;
      }
      this.$prompt('确认审核拒绝所选商品吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.check({
              id:this.multipleSelection.map(el=>el.id).join(','),
              status:5,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
        }).catch(() => {
          
        });
    },
    handleResolve(row) {
      this.$prompt('确认审核通过吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.check({
              id:row.id,
              status:10,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
        }).catch(() => {
          
        });
    },
    handleReject(row) {
      this.$prompt('确认审核拒绝吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPlaceholder:'审核备注'
        }).then(({ value }) => {
            value = value || '';
            apiObj.check({
              id:row.id,
              status:5,
              checkRemark:value.trim()
          }).then(() => {
            this.success();
            this.handleList();
          });
          this.success();
        }).catch(() => {
          
        });
    },
    handleBathDelRows() {
        if (validatenull(this.currentSelectedRowIds)) {
          this.$notify({
            showClose: true,
            message: "请至少选择一行要删除的数据",
            type: "error"
          });
          return false;
        }
        this.$confirm('是否确认删除所选择记录吗', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.bachDeleting = true;
          apiObj.removeByIds(
            this.currentSelectedRowIds
          ).then(() => {
              this.bachDeleting = false;
              this.handleList();
              this.$message({
                showClose: true,
                message: "成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            })
            .catch(() => {
              this.bachDeleting = false;
            });
        });
      },
    
     
      hasChanged(params1,params2){
        return Object.keys(params1).some(key=>params2[key] != params1[key]);
    },
    handleSearchChange(params) {
      if(this.hasChanged(params,this.tableQueryParam)){
        this.page.currentPage = 1;
      }
        this.tableQueryParam = params;
        this.handleList();
      },
      
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done, reject) {
        apiObj.update(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "修改成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },      
      
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done, reject) {
        apiObj.create(row)
          .then(() => {
            this.handleList();
            this.$message({
              showClose: true,
              message: "添加成功",
              type: "success"
            });
            done();
          })
          .catch(() => {
            reject();
          });
      },
      handleRefreshChange() {
        this.handleList();
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList() {
        this.tableLoading = true;
        apiObj.list({
          pageNo: this.page.currentPage,
          pageSize: this.page.pageSize,
          ...this.tableQueryParam
        })
          .then(data => {
            this.tableData = data.data || data.dataList || [];
            this.page.total = data.total;
            this.tableLoading = false;
          })
          .catch(() => {
            this.tableLoading = false;
          });
      },     
      
      handleDel(row, index) {
        this.$confirm('是否确认删除', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            apiObj.removeById(
              row.id
            ).then(() => {
              this.handleList();
              this.$message({
                showClose: true,
                message: "删除成功",
                type: "success"
              });
              this.$refs.crud.selectClear();
            });
          })
          .catch(() => {});
      },    
      handleExport() {
        this.downloadLoading = true;
        apiObj.list({
          pageNo: 1,
          pageSize: 3000,
          ...filterForm(this.$refs.crud.searchForm)
        }).then(res => {
          import("@/vendor/Export2Excel").then(excel => {
            const tHeader = ["优选商品状态","商品上线状态","商品审核状态","","商品名称","排序值","创建时间","审核人","审核备注","创建人","修改时间","修改人"];
            const filterVal = ["status","goodsStatus","goodsCheckStatus","title","sortNum","createTime","checkOperator","checkRemark","creator","modifyTime","modifier"];
            const data = this.formatJson(filterVal, res.data || res.dataList);
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: "精选商品" + nowDate()
            });
            this.downloadLoading = false;
          });
        });
      },
      formatJson(filterVal, jsonData) {      
        return jsonData.map(v =>
          filterVal.map(j => {
            return getLabelFromDicV2(this.$refs.crud.DIC,j,v[j]);
          })
        );
      }
    }
  };
  </script>
